package com.request.service.impl.shop.kx;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.KxDistribueErrorCodeEnum;
import com.request.common.enums.SignTypeEnum;
import com.request.common.utils.HttpUtils;
import com.request.common.utils.SignUtils;
import com.request.entity.PhoneOrderAvailable;
import com.request.entity.PhoneOrderWaitPush;
import com.request.entity.out.PushOrderForKxDistribute;
import com.request.service.PushOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Create DateTime: 2020-04-23 10:42
 *
 * 

 */
@Slf4j
@Service
public class KxDistributePushOrderProcessor implements PushOrderProcessor {


    @Resource
    private RedisService redisService;
    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendRequest(PhoneOrderWaitPush phoneOrderWaitPush) {
        handlerOrderExecutor.execute(() -> executeSend(phoneOrderWaitPush));
    }

    private void executeSend(PhoneOrderWaitPush phoneOrderWaitPush) {
        String result = null;
        PhoneOrderAvailable pa = phoneOrderWaitPush.getPhoneOrderAvailable();
        PushOrderForKxDistribute pushOrderForKxDistribute = new PushOrderForKxDistribute();
        try {

            TreeMap<String, String> signMap = new TreeMap<>();
            signMap.put("a", phoneOrderWaitPush.getAppKey());
            signMap.put("b", phoneOrderWaitPush.getAppId());
            signMap.put("c", pa.getPlatformOrderNo());
            signMap.put("d", pa.getPhoneNum());
            signMap.put("e", pa.getOrderPrice().toPlainString());
            signMap.put("f", pa.getPhoneOperator());
            signMap.put("g", phoneOrderWaitPush.getAppKey());
            String sign = SignUtils.generateSignature(signMap, SignTypeEnum.SHA256);
            pushOrderForKxDistribute.setOrderExpireTime(pa.getOrderExpireTime())
                    .setOrderPrice(pa.getOrderPrice())
                    .setPhoneNum(pa.getPhoneNum())
                    .setPhoneOperator(pa.getPhoneOperator())
                    .setAppId(phoneOrderWaitPush.getAppId())
                    .setSign(sign)
                    .setOrderNo(pa.getPlatformOrderNo())
                    .setProvince(pa.getProvince())
                    .setCity(pa.getCity())
                    .setOrderCreateTime(pa.getCreateTime());

            try {
                log.info("【魁信配单】配单推送参数:{}", pushOrderForKxDistribute.toString());
                result = sendRequestForPushOrder(phoneOrderWaitPush.getPushSite(), pushOrderForKxDistribute);
                log.info("【魁信配单】配单推送返回参数:{}", result);
            } catch (Exception e) {
                savePushOrderForException(phoneOrderWaitPush);
                savePushOrderForSuccess(pa.getPlatformOrderNo());
                log.info("【魁信配单】【推单】发送请求出现异常：", e);
                return;
            }

            JSONObject jsonResult = JSON.parseObject(result);
            String code = jsonResult.getString("code");

            if (KxDistribueErrorCodeEnum.FAIL.getCode().equals(code)) {
                log.info("【魁信配单】【推单】响应状态失败,状态为：{}", code);
                savePushOrderForFailed(phoneOrderWaitPush);
                return;
            }
            if (!KxDistribueErrorCodeEnum.SUCCESS.getCode().equals(code)) {
                String msg = jsonResult.getString("msg");
                throw new RuntimeException("推送订单商户相应失败，相应的状态码为 : "+ code + ",对应的信息为 : " + msg + ",订单号为：{}" + pa.getPlatformOrderNo());
            }
            savePushOrderForSuccess(pa.getPlatformOrderNo());
        } catch (Exception e) {
            savePushOrderForSuccess(pa.getPlatformOrderNo());
            log.error("【测试】【推送订单】推送订单失败，待推送订单信息为：{}, 请求参数为：{}, 商户响应结果为：{}, 详细错误信息为：",
                    phoneOrderWaitPush, pushOrderForKxDistribute, result, e);
        }
    }

    /**
     * 发送Http请求
     *
     * @param url              请求路径
     * @param pushOrderForKxDistribute 参数
     * @return 响应结果
     */
    private String sendRequestForPushOrder(String url, PushOrderForKxDistribute pushOrderForKxDistribute) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(pushOrderForKxDistribute);
        String paramJson = JSON.toJSONString(paramMap);
        return HttpUtils.jsonPost(url, paramJson);
    }

    /**
     * 放入失败队列
     */
    private void savePushOrderForFailed(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_RECORD, JSON.toJSONString(phoneOrderWaitPush));
    }

    /**
     * 放入成功队列
     */
    private void savePushOrderForSuccess(String platformOrderNo) {
        redisTemplate.opsForValue().set(RedisConstant.PUSH_ORDER_WAIT_PUSH_SUCCESS + platformOrderNo, platformOrderNo, 10, TimeUnit.MINUTES);
    }

    /**
     * 放入发送出现异常的队列
     */
    private void savePushOrderForException(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_EXCEPTION, JSON.toJSONString(phoneOrderWaitPush));
    }
}
